﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Drawing;
using com.lover.astd.updater.json;

namespace com.lover.astd.updater
{
    public class CommonUtils
    {
        private static List<string> _md5ExceptDir = null;
        public static JsonObjectCollection getLocalMd5(List<string> md5ExceptDir)
        {
            _md5ExceptDir = md5ExceptDir;
            string basedir = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            DirectoryInfo dirinfo = new DirectoryInfo(basedir);
            JsonObjectCollection obj = generateDirMd5(dirinfo, "");
            return obj;
        }

        private static string generateFileMd5(string filePath)
        {
            FileInfo finfo = new FileInfo(filePath);
            if (!finfo.Exists) return "";
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            FileStream stream = finfo.OpenRead();
            byte[] hash_bytes = provider.ComputeHash(stream);
            stream.Close();
            string md5str = BitConverter.ToString(hash_bytes);
            md5str = md5str.Replace("-", "");
            return md5str;
        }

        private static JsonObjectCollection generateDirMd5(DirectoryInfo dirinfo, string dirPath)
        {
            JsonObjectCollection whole_jobj = new JsonObjectCollection();
            whole_jobj.Name = dirPath;
            
            string path = dirPath == "" ? "" : dirPath + "/";

            DirectoryInfo[] dirinfos = dirinfo.GetDirectories();
            for (int i = 0, len = dirinfos.Length; i < len; i++)
            {
                DirectoryInfo dinfo = dirinfos[i];
                if (dinfo.Name == "." || dinfo.Name == ".." || _md5ExceptDir.Contains(dinfo.Name)) continue;
                JsonObjectCollection sub_obj = generateDirMd5(dinfo, path + dinfo.Name);

                IEnumerator<JsonObject> sub_enumer = sub_obj.GetEnumerator();
                while (sub_enumer.MoveNext())
                {
                    JsonObject item = sub_enumer.Current;
                    whole_jobj.Add(item);
                }
            }

            FileInfo[] finfos = dirinfo.GetFiles();
            for (int i = 0, len = finfos.Length; i < len; i++)
            {
                FileInfo finfo = finfos[i];
                string md5str = generateFileMd5(finfo.FullName);
                md5str = md5str.ToLower();
                JsonStringValue fmd5 = new JsonStringValue();
                fmd5.Name = path + finfo.Name;
                fmd5.Value = md5str;
                whole_jobj.Add(fmd5);
            }
            return whole_jobj;
        }
    }
}
